package com.xl.web.service.dict;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xl.base.annotation.DataSource;
import com.xl.base.page.BasePage;
import com.xl.base.service.BaseService;
import com.xl.core.enums.SourceEnum;
import com.xl.core.util.StringUtil;
import com.xl.web.dao.dict.DictDao;
import com.xl.web.entity.dict.DictBase;

@Service(value = "dictService")
public class DictService<T extends DictBase> extends BaseService<DictBase> {

	@Autowired
	private DictDao<DictBase> dictDao;

	@Override
	public DictDao<DictBase> getDao() {
		return this.dictDao;
	}

	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public DictBase getDictLabel(DictBase dictBase) {
		return getDao().getDictLabel(dictBase);
	}

	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public DictBase getDictName(DictBase dictBase) {
		return getDao().getDictName(dictBase);
	}

	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public List<DictBase> getDictList(Object dictType) {
		return getDao().getDictList(dictType);
	}

	/**
	 * 获取字典类型的列表
	 */
	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public List<DictBase> queryTypeByList(BasePage page) throws Exception {
		Integer rowCount = getDao().queryTypeByCount(page);
		page.getPager().setRowCount(rowCount);
		return getDao().queryTypeByList(page);
	}

	/**
	 * 字典类型添加与修改
	 * 
	 * @param dictBase
	 * @throws Exception
	 */
	public void addTypeSave(DictBase dictBase, String oldDictType)
			throws Exception {
		// 新增保存
		if (StringUtil.isEmpty(oldDictType)) {
			super.add(dictBase);
		} else {

			List<DictBase> dictList = getDictList(oldDictType);
			// 更新保存
			for (DictBase dict : dictList) {
				dict.setDictType(dictBase.getDictType());
				dict.setDictTypeName(dictBase.getDictTypeName());
				super.updateBySelective(dict);
			}
		}
	}

	/**
	 * 字典类型删除
	 * 
	 * @param dictBase
	 * @throws Exception
	 */
	public void deleteDictType(DictBase dictBase) throws Exception {

		// 物理删除
		if (dictBase == null || StringUtil.isEmpty(dictBase.getDictType())) {
			return;
		}
		List<DictBase> dictList = getDictList(dictBase.getDictType());
		// 更新保存
		for (DictBase dict : dictList) {
			super.delete(dict);
		}
	}

	/**
	 * 验证字典是否存在
	 * 
	 * @param dictBase
	 * @return
	 */
	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public List<DictBase> checkDictExist(DictBase dictBase) {
		return getDao().checkDictExist(dictBase);
	}

	/**
	 * 根据Type获取到字典类型
	 * 
	 * @param dictBase
	 * @return
	 */
	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public DictBase queryByType(DictBase dictBase) {
		return getDao().queryByType(dictBase);
	}

	/**
	 * 获取多个字典值
	 * 
	 * @param dictBase
	 * @return
	 */
	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public List<DictBase> getDictLabels(DictBase dictBase) {
		return getDao().getDictLabels(dictBase);
	}
}